package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/dtos"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

// 添加产品传输配置
func AddProductTransport(pt models.ProductTransport, ctx context.Context, dic *di.Container) (id string, edgeXerr errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	addProductTransport, err := dbClient.AddProductTransport(pt)
	if err != nil {
		return "", errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf(
		"Product Transport created on DB successfully. Product Transport ID: %s, Correlation-ID: %s ",
		addProductTransport.Id,
		correlation.FromContext(ctx),
	)

	return addProductTransport.Id, nil
}

// AllTransportsByProductId 根据产品id分页查询产品传输配置
func AllTransportsByProductId(offset int, limit int, productId string, dic *di.Container) (productTransports []dtos.ProductTransport, totalCount uint32, err errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	transports, err := dbClient.AllTransportsByProductId(offset, limit, productId)
	if err == nil {
		totalCount, err = dbClient.AllTransportCountByProductId(productId)
	}
	if err != nil {
		return productTransports, totalCount, errors.NewCommonEdgeXWrapper(err)
	}
	productTransports = make([]dtos.ProductTransport, len(transports))
	for i, pt := range transports {
		productTransports[i] = dtos.FromProductTransportModelToDto(pt)
	}
	return productTransports, totalCount, nil
}

// ProductTransportDelete 批量删除产品传输配置
func ProductTransportDelete(productTransportIds []string, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)

	err := dbClient.ProductTransportDelete(productTransportIds)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	return nil
}

// 更新产品传输配置
func UpdateProductTransport(productTransport models.ProductTransport, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.UpdateProductTransport(productTransport)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	lc.Debugf("产品传输配置更新完成")
	return nil

}
